﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Diagnostics;

namespace System.Windows.Media.DirectShow.Filters
{
    internal class WaveWriterInputPin : BaseInputPin
    {

        private AMMediaType[] _mediaTypes = new AMMediaType[] { new AMMediaType {
            MajorType = MediaMajorTypes.Audio,
            SubType = MediaSubTypes.PCM,
        }};

        private WaveWriterOutputPin outputPin;

        public WaveWriterInputPin(IBaseFilter filter, WaveWriterOutputPin outputPin)
            : base(filter)
        {
            this.outputPin = outputPin;
        }

        public override bool ReceiveCanBlock
        {
            get { return false; }
        }

        protected override AllocatorProperties GetAllocatorRequirements()
        {
            return new AllocatorProperties { BuffersCount = 8, BufferSize = 4096 };
        }

        protected override void Receive(IMediaSample sample)
        {
            sample.AddRef();

            try
            {
                sample.StartMediaTime += WaveWriter.WaveHeaderSize;
                sample.EndMediaTime += WaveWriter.WaveHeaderSize;
                this.outputPin.ProcessSample(sample);
            }
            finally
            {
                sample.Release();
            }

            if (this.IsPullMode)
                this.RequestNextSample(sample);
        }

        protected override void EndOfStream()
        {
            base.EndOfStream();

            this.outputPin.Flush();
            this.outputPin.DeliverEndOfStream();
        }

        public override System.Collections.Generic.IEnumerable<AMMediaType> MediaTypes
        {
            get { return _mediaTypes; }
        }

        public override string Name
        {
            get { return "Wave in"; }
        }
    }
}
